<template>
  <div class="common-layout linear-gradient">
    <el-container style="margin-top: -30px">
      <el-header class="header-container">
        <div class="headerTitle">查询条件</div>
        <div class="header-content">
          <el-form :model="headerSearchForm" label-width="auto" class="header-search-form">
            <el-form-item label="产线">
              <el-select v-model="headerSearchForm.productionLine" placeholder="所有产线" style="min-width: 160px">
                <el-option v-for="item in productionLineOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="原卷号">
              <el-input v-model="headerSearchForm.entId" placeholder="请输入卷号" />
            </el-form-item>
            <el-form-item label="销售合同编号">
              <el-input v-model="headerSearchForm.orderNo" placeholder="请输入销售合同编号" />
            </el-form-item>
            <el-form-item label="钢种类型">
              <el-input v-model="headerSearchForm.steelGrade" placeholder="请输入钢种类型" />
            </el-form-item>
            <el-form-item label="重量不符标识">
              <el-select v-model="headerSearchForm.wtMisMatchFlag" placeholder="请选择" clearable style="width: 160px">
                <el-option label="正常" value="0" />
                <el-option label="不符" value="1" />
              </el-select>
            </el-form-item>
          </el-form>
          <div class="header-buttons">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button type="primary" @click="handleReset">重置</el-button>
            <el-button type="primary" @click="exportExcel">导出</el-button>
            <!-- <el-button type="primary" @click="handleAdd">添加</el-button> -->
          </div>
        </div>
      </el-header>
      <el-main>
        <div class="table-container-main">
          <el-table
            :data="tableData"
            :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
            :row-style="rowStyle"
            v-loading="loading"
            ref="tableRef"
          >
            <el-table-column prop="serialNumber" label="序号" fixed="left">
              <template #default="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="entId" label="卷号" min-width="160px" fixed="left" sortable />
            <el-table-column prop="productLine" label="产线" min-width="120px" fixed="left" sortable />
            <el-table-column prop="steelGrade" label="钢种类型" min-width="120px" fixed="left" />
            <el-table-column prop="orderNo" label="销售合同编号" min-width="160px" sortable />
            <el-table-column prop="yieldRate" label="成材率">
              <template #default="scope">
                {{ scope.row.yieldRate * 100 + '%' }}
              </template>
            </el-table-column>
            <el-table-column prop="slitNum" label="分卷数量" />
            <el-table-column prop="slitWeight" label="单卷分切重量[t]" width="160px" />
            <el-table-column prop="lossWeight" label="分切损耗重量[t]" width="160px" />
            <el-table-column prop="orderUnitWTMin" label="订单允许的最小单件重量[t]" width="120px" />
            <el-table-column prop="orderUnitWTMax" label="订单允许的最大单件重量[t]" width="120px" />
            <el-table-column prop="inMatWt" label="入口材料重量[t]" />
            <el-table-column prop="inMatThick" label="入口材料厚度[mm]" width="100px" />
            <el-table-column prop="inMatWidth" label="入口材料宽度[mm]" width="100px" />
            <el-table-column prop="inMatLen" label="入口材料长度[m]" />
            <el-table-column prop="outMatLen" label="出口材料长度[m]" width="100px" />
            <el-table-column prop="outMatWidth" label="出口材料宽度[mm]" width="100px" />
            <el-table-column prop="outMatThick" label="出口材料厚度[mm]" width="100px" />
            <el-table-column prop="wtMisMatchFlag" label="重量不符标识">
              <template #default="scope">
                <span v-if="scope.row.wtMisMatchFlag === '0'"><el-tag type="primary">正常</el-tag></span>
                <span v-else><el-tag type="danger">不符</el-tag></span>
              </template>
            </el-table-column>
            <el-table-column prop="reason" label="重量不符原因描述" show-overflow-tooltip min-width="200px" />
            <el-table-column prop="defectCode" label="缺陷代码" />
            <el-table-column prop="defectClass" label="缺陷等级" />
            <el-table-column prop="crew" label="班组" />
            <el-table-column prop="createTime" label="记录创建时间" min-width="200px" />
          </el-table>
        </div>
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>
  </div>

  <el-dialog v-model="dialogVisible" :title="dialogTitle" :before-close="handleClose" ref="dialogRef" @closed="cancel">
    <el-form :model="dialogForm" label-width="auto" class="dialog-form">
      <div style="height: 70vh; margin-left: 40px">
        <el-scrollbar>
          <el-form-item label="卷号">
            <el-text>{{ dialogForm.entId }}</el-text>
          </el-form-item>
          <el-form-item label="销售合同编号">
            <el-text>{{ dialogForm.orderNo }}</el-text>
          </el-form-item>
          <el-form-item label="产线">
            <el-text>{{ dialogForm.productLine }}</el-text>
          </el-form-item>
          <el-form-item label="钢种类型">
            <el-text>{{ dialogForm.steelGrade }}</el-text>
          </el-form-item>
          <el-form-item label="成材率">
            <el-text>{{ dialogForm.yieldRate + '%' }}</el-text>
          </el-form-item>
          <el-form-item label="分卷数量">
            <el-text>{{ dialogForm.slitNum }}</el-text>
          </el-form-item>
          <el-form-item label="单卷分切重量">
            <el-text>{{ dialogForm.slitWeight }}</el-text>
          </el-form-item>
          <el-form-item label="重量不符标识">
            <!-- <el-text>{{ dialogForm.wtMisMatchFlag }}</el-text> -->
            <span v-if="dialogForm.wtMisMatchFlag === '0'"><el-tag type="primary">正常</el-tag></span>
            <span v-else-if="dialogForm.wtMisMatchFlag === '1'"><el-tag type="danger">不符</el-tag></span>
          </el-form-item>
          <el-form-item label="重量不符原因描述">
            <el-text>{{ dialogForm.reason }}</el-text>
          </el-form-item>
          <el-form-item label="分切损耗重量">
            <el-text>{{ dialogForm.lossWeight }}</el-text>
          </el-form-item>
          <el-form-item label="订单允许的最小单件重量">
            <el-text>{{ dialogForm.orderUnitWTMin }}</el-text>
          </el-form-item>
          <el-form-item label="订单允许的最大单件重量">
            <el-text>{{ dialogForm.orderUnitWTMax }}</el-text>
          </el-form-item>
          <el-form-item label="入口材料重量">
            <el-text>{{ dialogForm.inMatWt }}</el-text>
          </el-form-item>
          <el-form-item label="入口材料厚度">
            <el-text>{{ dialogForm.inMatThick }}</el-text>
          </el-form-item>
          <el-form-item label="入口材料宽度">
            <el-text>{{ dialogForm.inMatWidth }}</el-text>
          </el-form-item>
          <el-form-item label="入口材料长度">
            <el-text>{{ dialogForm.inMatLen }}</el-text>
          </el-form-item>
          <el-form-item label="出口材料长度">
            <el-text>{{ dialogForm.outMatLen }}</el-text>
          </el-form-item>
          <el-form-item label="出口材料宽度">
            <el-text>{{ dialogForm.outMatWidth }}</el-text>
          </el-form-item>
          <el-form-item label="出口材料厚度">
            <el-text>{{ dialogForm.outMatThick }}</el-text>
          </el-form-item>
          <el-form-item label="缺陷代码">
            <el-text>{{ dialogForm.defectCode }}</el-text>
          </el-form-item>
          <el-form-item label="缺陷等级">
            <el-text>{{ dialogForm.defectClass }}</el-text>
          </el-form-item>
          <el-form-item label="班组">
            <el-text>{{ dialogForm.crew }}</el-text>
          </el-form-item>
          <el-form-item label="记录创建时间">
            <el-text>{{ dialogForm.createTime }}</el-text>
          </el-form-item>
        </el-scrollbar>
      </div>
    </el-form>
  </el-dialog>
</template>
<script lang="ts">
  import { ref, reactive, onMounted, onUnmounted, nextTick, defineComponent } from 'vue';
  import { ElMessage, ElMessageBox, ElTable } from 'element-plus';
  import { api } from '/@/api/VolumeDivisionOptimization/index';
  import * as XLSX from 'xlsx';

  interface SearchForm {
    productionLine: string;
    entId: string;
    orderNo: string;
    steelGrade: string;
    wtMisMatchFlag: string;
  }

  export default defineComponent({
    name: 'DataDictionary',
    setup() {
      // 表单数据
      const headerSearchForm = reactive<SearchForm>({
        productionLine: '',
        entId: '',
        orderNo: '',
        steelGrade: '',
        wtMisMatchFlag: '',
      });

      const drawerData = ref([
        { name: '全流程重量不符追溯分析', url: '/yiledAndSubsection/DefectYieldAnalysis' },
        { name: '历史卷重不符统计及优化建议', url: '/volumeDivisionOptimization/index' },
        { name: '生产计划-动态分切建议', url: '/volumeDivisionOptimization/list' },
      ]);

      // 表格数据
      const tableData = ref<any>([]);
      const tableRef = ref<InstanceType<typeof ElTable>>();

      let dialogVisible = ref(false);
      let dialogTitle = ref('');
      const loading = ref(false);

      // 分页数据
      const pagination = reactive({
        currentPage: 1,
        pageSize: 10,
        total: 1,
      });

      // 下拉框选项
      const productionLineOptions = ref([
        { value: '', label: '所有产线' },
        { value: 'CAL2150', label: '2#连退' }, // CAL2150连退
        { value: 'CAL1630', label: '3#连退' }, // CAL1630连退
        { value: 'TCM2280', label: '3#酸轧' }, // TCM2280酸轧
        { value: 'CGL1870', label: '5#镀锌' }, // CGL1870镀锌
        { value: 'RCL2150', label: '4#重卷' }, // CAL2150重卷
        { value: 'RCL1630', label: '5#重卷' }, // CAL1630重卷
        { value: 'RCL1870', label: '6#重卷' }, // CGL1870重卷
      ]);

      const dialogForm = reactive({
        indocno: 0, // 主键
        entId: '', // 原卷号（上游系统提供的唯一物料标识）
        orderNo: '', // 销售合同编号（格式示例：SO20250510-001）
        productLine: '', // 产线编码（取值范围：CAL1630/CAL2150/CGL1870/TCM2280）
        orderUnitWTMin: '', // 订单允许的最小单件重量（单位：千克，精度0.01kg）
        orderUnitWTMax: '', // 订单允许的最大单件重量（单位：千克，精度0.01kg）
        inMatWt: '', // 入口材料重量（单位：吨，精度0.001吨=1kg）
        yieldRate: '', // '成材率（计算公式：(分卷重量*分卷数)/入口材料重量*100%）
        slitNum: '', // 分卷数量（默认值1，取值范围1-32767）
        slitWeight: '', // 单卷分切重量（单位：吨，精度0.001吨=1kg）
        wtMisMatchFlag: '', // 重量不符标识（0-正常，1-不符，需填写REASON字段）
        reason: '', // 重量不符原因描述（当FLAG=1时必填）
        createTime: '', // 记录创建时间（自动获取系统时间）
        lossWeight: '', // 分切损耗重量（计算公式：入口材料重量 - (分卷数量*单卷分切重量)，单位：吨，精度0.001吨=1kg）
        steelGrade: '', // 钢种类型
        inMatThick: '', // 入口材料厚度
        inMatWidth: '', // 入口材料宽度
        inMatLen: '', // 入口材料长度
        outMatLen: '', // 出口材料长度
        outMatWidth: '', // 出口材料宽度
        outMatThick: '', // 出口材料厚度
        defectCode: '', // 缺陷代码
        defectClass: '', // 缺陷等级
        crew: '', // 班组
      });

      const rowStyle = (row: any, rowIndex: number) => {
        if (!row) return {};
        if (row.row.wtMisMatchFlag === '1') {
          return { backgroundColor: '#ffe6e6' };
        }
        return {};
      };

      const handleClose = (done: () => void) => {
        ElMessageBox.confirm('确定要关闭窗口吗?', { confirmButtonText: '确定', cancelButtonText: '取消' })
          .then(() => {
            done();
          })
          .catch(() => {
            // catch error
          });
      };

      const cancel = () => {
        dialogVisible.value = false;
        Object.assign(dialogForm, {
          indocno: null,
          productionLine: '',
          areaDescription: '',
          areaCode: '',
          deviceDescription: '',
          deviceCode: '',
          dicVariableName: '',
          dicVariableDescription: '',
          inDataSource: '1',
          dicVariableProperty: '',
          enable: '0',
          toc: '',
          tom: '',
        });
      };

      // TODO TOC创建时间/TOM修改时间
      const dialogFormSubmit = async () => {
        try {
          let param: any = { ...dialogForm };
          param.enable = Number.parseInt(param.enable);
          if (dialogTitle.value === '修改') {
            await api.update(param);
          } else {
            await api.add(param);
          }
        } catch (error) {
          ElMessage.error('操作数据失败');
        } finally {
          cancel();
          fetchTableData();
        }
      };

      // 窗口大小变化处理
      const handleResize = () => {
        nextTick(() => {
          // 这里可以添加表格自适应高度的逻辑
        });
      };

      // 获取表格数据
      const fetchTableData = async () => {
        loading.value = true;
        try {
          const param = {
            page: {
              pageIndex: pagination.currentPage,
              pageSize: pagination.pageSize,
            },
            dto: {
              productLine: headerSearchForm.productionLine,
              entId: headerSearchForm.entId,
              orderNo: headerSearchForm.orderNo,
              steelGrade: headerSearchForm.steelGrade,
              wtMisMatchFlag: headerSearchForm.wtMisMatchFlag,
            },
          };
          const res = await api.page(param);
          tableData.value = res.data.data.records;
          pagination.total = res.data.count;
          loading.value = false;
        } catch (error) {
          loading.value = false;
          ElMessage.error('获取数据失败');
        }
      };

      // 查询方法
      const handleSearch = () => {
        pagination.currentPage = 1;
        fetchTableData();
      };

      // 重置方法
      const handleReset = () => {
        (Object.keys(headerSearchForm) as Array<keyof SearchForm>).forEach((key) => {
          headerSearchForm[key] = '';
        });
        handleSearch();
      };

      // 导出方法
      const exportExcel = () => {
        if (!tableData.value.length) {
          ElMessage.error('导出Excel失败: 当前暂无数据');
          return;
        }

        try {
          // 动态获取表格列配置
          const columns = tableRef.value?.columns;

          if (!columns || !(Array.isArray(columns) && columns.length)) {
            ElMessage.error('导出Excel失败: 表格列配置错误');
            return;
          }

          // 添加新的属性到 headerMap
          const headerMap: Record<string, string> = {
            indocno: '序号',
          };

          // 构建字段到标签的映射
          columns.forEach((column: any) => {
            if (column.property && column.property !== 'serialNumber') {
              headerMap[column.property] = column.label;
            }
          });

          delete headerMap['serialNumber'];

          // 构建字段名数组
          const columnProperties = Object.keys(headerMap);

          // 转换数据为 worksheet
          const ws = XLSX.utils.json_to_sheet(tableData.value, { header: columnProperties });

          // 添加中文表头
          const headerRow = Object.values(headerMap);
          XLSX.utils.sheet_add_aoa(ws, [headerRow], { origin: 'A1' });

          // 创建 workbook 并添加 worksheet
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

          // 格式化日期和时间
          const formattedDateTime = new Date()
            .toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
              hour12: false,
            })
            .replace(/\//g, '-')
            .replace(/\s/g, '_')
            .replace(/:/g, '-');

          // 生成 Excel 文件并下载
          XLSX.writeFile(wb, '动态分切建议数据' + formattedDateTime + '.xlsx');
          ElMessage.success('导出成功');
        } catch (error: any) {
          ElMessage.error('导出Excel失败: ' + error.message);
          console.error('导出Excel时出错:', error);
        }
      };

      // 添加方法
      const handleAdd = () => {
        dialogVisible.value = true;
        dialogTitle.value = '新增';
      };

      // 编辑方法
      const handleEdit = (row: any) => {
        dialogVisible.value = true;
        dialogTitle.value = '修改';
        Object.assign(dialogForm, { ...row });
      };

      // 详情方法
      const handleDetail = (row: any) => {
        dialogVisible.value = true;
        dialogTitle.value = '详情';
        Object.assign(dialogForm, { ...row });
      };

      // 删除方法
      const handleDelete = async (row: any) => {
        try {
          await api.delete(row.indocno);
        } catch (error) {
          ElMessage.error('删除失败');
        } finally {
          fetchTableData();
        }
      };

      // 分页大小变化
      const handleSizeChange = (val: number) => {
        pagination.pageSize = val;
        fetchTableData();
      };

      // 页码变化
      const handleCurrentChange = (val: number) => {
        pagination.currentPage = val;
        fetchTableData();
      };

      // 生命周期钩子
      onMounted(() => {
        fetchTableData();
        window.addEventListener('resize', handleResize);
      });

      onUnmounted(() => {
        window.removeEventListener('resize', handleResize);
      });

      return {
        headerSearchForm,
        tableData,
        pagination,
        handleSearch,
        handleReset,
        handleAdd,
        handleEdit,
        handleDetail,
        handleDelete,
        handleSizeChange,
        handleCurrentChange,
        dialogVisible,
        dialogTitle,
        dialogForm,
        dialogFormSubmit,
        cancel,
        handleClose,
        drawerData,
        loading,
        exportExcel,
        productionLineOptions,
        tableRef,
        rowStyle,
      };
    },
  });
</script>
<style lang="less" scoped>
  @border-radius: 8px;
  @primary-color: #2c69e8;
  @box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  .common-layout {
    width: 99vw;
    height: 100vh;
    position: relative;
    background-color: #fff;
    overflow: hidden;

    &.linear-gradient {
      background-image: linear-gradient(to top, white, @primary-color) !important;
    }
  }
  .header-container {
    width: 98%;
    margin-left: 1%;
    margin-top: 4vh;
    margin-bottom: 2vh;
    border-radius: @border-radius;
    height: 11vh;
    background-color: #fff;
    box-shadow: @box-shadow;

    .headerTitle {
      width: 100%;
      height: 4vh;
      display: flex;
      align-items: center;
    }
    .header-content {
      width: 100%;
      height: 6vh;
      display: flex;
      justify-content: space-between;

      .header-search-form {
        height: auto;
        display: grid;
        grid-template-columns: repeat(5, minmax(200px, 1fr));
        gap: 12px 10px; /* 行间距 列间距 */
        position: relative;
        z-index: 1;
        justify-content: start;
        width: calc(100% - 360px);
        padding-right: 12px;
        box-sizing: border-box;
      }

      .header-buttons {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        gap: 10px;
        flex: 0 0 340px; /* 固定按钮区域宽度，保证左侧网格等距 */
        margin-top: -10px;

        .el-button {
          min-width: 80px;
        }
      }
    }
  }

  .table-container-main {
    border-radius: @border-radius;
    height: 71vh;
    background-color: #fff;
    box-shadow: @box-shadow;
    display: flex;
    align-items: center;
    margin-top: -2vh;

    .el-table {
      width: calc(100% - 40px);
      height: calc(100% - 40px);
      margin-left: 20px;
    }
  }

  .pagination {
    margin-top: 2vh;
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
  }
</style>
